package com.pmcc.platform.shopping.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pmcc.platform.giftGoods.entity.Goods;
import com.pmcc.platform.giftGoods.repository.GoodsRepository;
import com.pmcc.platform.salesman.entity.Salesman;
import com.pmcc.platform.salesman.repository.SalesmanRepository;
import com.pmcc.platform.shop.service.ShopInfoService;
import com.pmcc.platform.shop.vo.AddressVo;
import com.pmcc.platform.shopping.entity.*;
import com.pmcc.platform.shopping.enums.GiftChange;
import com.pmcc.platform.shopping.repository.*;
import com.pmcc.platform.shop.entity.ShopInfo;
import com.pmcc.platform.shop.repository.ShopInfoRepository;
import com.pmcc.platform.shopping.vo.*;
import com.pmcc.platform.user.entity.UserInfo;
import com.pmcc.platform.user.repository.UserInfoRepository;
import com.pmcc.utils.AntPage;
import com.pmcc.utils.ApiResultBean;
import com.pmcc.utils.MapUtil;
import com.pmcc.utils.StringUtil;

import com.pmcc.utils.wechat.GpsUtil;
import com.pmcc.utils.wechat.HttpClientUtil;
import com.pmcc.utils.wechat.WechatMiniConfig;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.omg.PortableServer.LIFESPAN_POLICY_ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class ShoppingService {

    @Autowired
    ShoppingRepository shoppingRepository;

    @Autowired
    ShoppingChangeLogRepository shoppingChangeLogRepository;

    @Autowired
    ShopInfoRepository shopInfoRepository;

    @Autowired
    GoodsGiftRepository goodsGiftRepository;

    @Autowired
    ShoppingGiftChangeLogRepository shoppingGiftChangeLogRepository;

    @Autowired
    ShopLiboryRepository shoppingLiboryRepository;

    @Autowired
    UserInfoRepository userInfoRepository;

    @Autowired
    SalesmanRepository salesmanRepository;

    @Autowired
    GoodsRepository goodsRepository;

    @Autowired
    ShopInfoService shopInfoService;

    @Autowired
    ShoppingApplyRepository shoppingApplyRepository;


    public ApiResultBean queryAllShopping(String name, String phone, AntPage antPage) {
        ApiResultBean apiResultBean = new ApiResultBean();
        Page<Shopping> list = shoppingRepository.findAllByDelFlagAndNameContainsAndPhoneContainsOrderByCreateTime("0", name, phone, antPage.getPageRequest());

        for (Shopping shopping : list) {
            ShopInfo shopInfo = shopInfoRepository.findOne(shopping.getShopId());
            shopping.setShopName(shopInfo.getName());
            Salesman salesman = salesmanRepository.findOne(shopInfo.getSalesmanId());
            shopping.setSalesmanName(salesman.getName());
            shopping.setSalesmanPhone(salesman.getPhone());
            int getNum = 0;
            int s = goodsGiftRepository.countShoppingNum(shopping.getId(), "1", "0");
            getNum = getNum + s;
            shopping.setGetNum(getNum);
        }
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setData(list, antPage);
        return apiResultBean;
    }


    public ApiResultBean querySalesman(String shoppingId) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(shoppingId)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("传入的售货员id不能为空");
            return apiResultBean;
        }
        Shopping shopping = shoppingRepository.findAllByIdAndDelFlag(shoppingId, "0");

        ShopInfo shopInfo = shopInfoRepository.findOne(shopping.getShopId());
        Salesman salesman = salesmanRepository.findOne(shopInfo.getSalesmanId());
        shopping.setSalesmanName(salesman.getName());
        shopping.setSalesmanPhone(salesman.getPhone());
        shopping.setShopName(shopInfo.getName());
        if (shopping == null) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("不存在该售货员");
            return apiResultBean;
        }

        int getNum = 0;
        int s = goodsGiftRepository.countShoppingNum(shoppingId, "1", "0");
        getNum = getNum + s;
        shopping.setGetNum(getNum);

        apiResultBean.setMsg("查询成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setData(shopping);
        return apiResultBean;
    }

    public ApiResultBean addShopping(Shopping shopping) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(shopping.getName())) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("姓名不能为空");
            return apiResultBean;
        }
        if (StringUtil.isEmpty(shopping.getPhone())) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("手机号不能为空");
            return apiResultBean;
        }
        if (StringUtil.isEmpty(shopping.getIsPerpetual())) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("临时导购字段不能为空不能为空");
            return apiResultBean;
        }
        if (StringUtil.isEmpty(shopping.getShopId())) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("店铺id不能为空");
            return apiResultBean;
        }

        Shopping shopping1 = new Shopping();
        shopping1.setName(shopping.getName());
        shopping1.setPhone(shopping.getPhone());
        shopping1.setIsPerpetual(shopping.getIsPerpetual());
        if (shopping.getIsPerpetual().equals("1")) {
            shopping1.setEndTime(shopping.getEndTime());
            shopping1.setStartTime(shopping.getStartTime());
        }
        shopping1.setShopId(shopping.getShopId());
        ShopInfo shopInfo = shopInfoRepository.findOne(shopping.getShopId());
        shopping1.setSalesmanId(shopInfo.getId());
        shoppingRepository.save(shopping1);

        ShoppingChangeLog shoppingChangeLog = new ShoppingChangeLog();
        shoppingChangeLog.setShoppingId(shopping1.getId());
        shoppingChangeLog.setShopId(shopping.getShopId());
        shoppingChangeLogRepository.saveAndFlush(shoppingChangeLog);


        apiResultBean.setMsg("添加成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }


    public ApiResultBean delShopping(String shoppingId) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(shoppingId)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("导购id不能为空");
            return apiResultBean;
        }
        Shopping shopping = shoppingRepository.findOne(shoppingId);
        shopping.setDelFlag("1");
        shoppingRepository.save(shopping);
        apiResultBean.setMsg("删除成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }

    public ApiResultBean modifyShopping(Shopping shopping) {
        ApiResultBean apiResultBean = new ApiResultBean();

        if (StringUtil.isEmpty(shopping.getId())) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("导购id不能为空");
            return apiResultBean;
        }
        Shopping shopping1 = shoppingRepository.findAllByIdAndDelFlag(shopping.getId(), "0");

        if (!shopping1.getShopId().equals(shopping.getShopId())) {

            //添加导购更换超市记录
            ShoppingChangeLog shoppingChangeLog = new ShoppingChangeLog();
            shoppingChangeLog.setShoppingId(shopping.getId());
            shoppingChangeLog.setShopId(shopping.getShopId());
            shoppingChangeLogRepository.save(shoppingChangeLog);
            //更换导购当前超市
            shopping.setShopId(shopping.getShopId());
            shoppingRepository.save(shopping);


        }
        if (shopping1 == null) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("导购不存在");
            return apiResultBean;
        }
        if (StringUtil.isNotEmpty(shopping.getIsPerpetual())) {
            shopping1.setIsPerpetual(shopping.getIsPerpetual());
            if (shopping.getIsPerpetual().equals("1")) {
                shopping1.setStartTime(shopping.getStartTime());
                shopping1.setEndTime(shopping.getEndTime());
            }
        }
        if (StringUtil.isNotEmpty(shopping.getPhone())) {
            shopping1.setPhone(shopping.getPhone());
        }
        if (StringUtil.isNotEmpty(shopping.getName())) {
            shopping1.setName(shopping.getName());
        }
        shoppingRepository.save(shopping1);
        apiResultBean.setMsg("修改导购个人信息成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }

    public ApiResultBean modifyShoppingChange(String shoppingId, String shopId) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(shoppingId) && StringUtil.isEmpty(shopId)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("导购id和店铺id不能为空");
            return apiResultBean;
        }
        Shopping shopping = shoppingRepository.findAllByIdAndDelFlag(shoppingId, "0");
        if (shopping == null) {
            apiResultBean.setMsg("导购不存在");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return apiResultBean;
        }
        ShopInfo shopInfo = shopInfoRepository.findAllByDelFlagAndId("0", shopId);
        if (shopInfo == null) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("店铺不存在");
            return apiResultBean;
        }
        //添加导购更换超市记录
        ShoppingChangeLog shoppingChangeLog = new ShoppingChangeLog();
        shoppingChangeLog.setShoppingId(shoppingId);
        shoppingChangeLog.setShopId(shopId);
        shoppingChangeLogRepository.save(shoppingChangeLog);
        //更换导购当前超市
        shopping.setShopId(shopId);
        shoppingRepository.save(shopping);


        apiResultBean.setMsg("改动成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);

        return apiResultBean;
    }

    public ApiResultBean queryShop(String shoppingId) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(shoppingId)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("导购id不能为空");
            return apiResultBean;
        }
        Shopping shopping = shoppingRepository.findAllByIdAndDelFlag(shoppingId, "0");
        if (StringUtil.isNotEmpty(shopping.getShopId())) {
            ShopInfo shopInfo = shopInfoRepository.findAllByDelFlagAndId("0", shopping.getShopId());
            apiResultBean.setMsg("查询成功");
            apiResultBean.setCode(ApiResultBean.SUCCESS);
            apiResultBean.setData(shopInfo);
        }
        return apiResultBean;
    }

    public String getUserUnionId(String openId, String accessToken) {
        List<UserInfo> userInfos1 = userInfoRepository.findAllByOppenIdAndDelFlag(openId, "0");
        if (userInfos1.size() > 0) {
            if (StringUtil.isEmpty(userInfos1.get(0).getName())) {
                String unionid = "";
                /*String accessToken = getAccessToken();*/
                String sendUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId;
                String json = HttpClientUtil.httpGetRequest(sendUrl);
                String json1 = "";
                try {
                    json1 = new String(json.getBytes("ISO-8859-1"), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(json1);


                if (jsonObject.containsKey("headimgurl")) {
                    userInfos1.get(0).setHeadimgurl((String) jsonObject.get("headimgurl"));
                }
                if (jsonObject.containsKey("sex")) {
                    userInfos1.get(0).setSex(jsonObject.get("sex") + "");
                }
                if (jsonObject.containsKey("city")) {
                    userInfos1.get(0).setCity(jsonObject.get("city") + "");
                }

                if (jsonObject.containsKey("country")) {
                    userInfos1.get(0).setCountry(jsonObject.get("country") + "");
                }
                if (jsonObject.containsKey("province")) {
                    userInfos1.get(0).setProvinces(jsonObject.get("province") + "");
                }
                if (jsonObject.containsKey("nickname")) {
                    userInfos1.get(0).setNickname(jsonObject.get("nickname") + "");
                }
                userInfoRepository.save(userInfos1);
            }
        }

        return null;
    }


    public ApiResultBean queryHistoryShop(String shoppingId) {

        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(shoppingId)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("id不能为空");
            return apiResultBean;
        }
        List<ShoppingChangeLog> shoppingChangeLogs = shoppingChangeLogRepository.findAllByShoppingIdAndDelFlagOrderByCreateTimeDesc(shoppingId, "0");
        int a = shoppingChangeLogRepository.countAllByShoppingIdAndDelFlag(shoppingId, "0");
        List<HistoryShopVo> historyShopVos = new ArrayList<>();
        if (shoppingChangeLogs.size() > 0) {
            for (ShoppingChangeLog shoppingChangeLog : shoppingChangeLogs) {
                HistoryShopVo historyShopVo = new HistoryShopVo();
                historyShopVo.setJoinTime(shoppingChangeLog.getCreateTime());
                ShopInfo shopInfo = shopInfoRepository.findOne(shoppingChangeLog.getShopId());
                historyShopVo.setShopName(shopInfo.getName());
                historyShopVo.setAddress(shopInfo.getAddress());
                historyShopVos.add(historyShopVo);
            }
        }
        apiResultBean.setMsg("查询成功");
        apiResultBean.setData(historyShopVos);
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }

    public ApiResultBean queryNearbyShop(String longitude, String latitude, String miniUserId, String shopName, AntPage antPage) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(longitude) || StringUtil.isEmpty(latitude)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("经纬度不能为空");
            return apiResultBean;
        }
        double lo = Double.parseDouble(longitude);
        double la = Double.parseDouble(latitude);
        String prapeze = latitude + "," + longitude;
        AddressVo addressVo = new AddressVo();
        try {
            addressVo = shopInfoService.gain(prapeze);
        } catch (Exception e) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("api接口错误");
            return apiResultBean;
        }
        String city = addressVo.getCity();
        Page<ShopInfo> shopInfos = shopInfoRepository.findAllByCityAndDelFlagAndNameContains(city, "0", shopName, antPage.getPageRequest());
        if (shopInfos.getSize() > 0) {
            HashMap<String, Integer> hashMap = new HashMap<>();
            for (ShopInfo shopInfo : shopInfos) {
                GlobalCoordinates source = new GlobalCoordinates(shopInfo.getLatitude(), shopInfo.getLongitude());
                GlobalCoordinates target = new GlobalCoordinates(la, lo);
                double meter1 = GpsUtil.getDistanceMeter(source, target, Ellipsoid.Sphere);
                int distance = (int) meter1;
                hashMap.put(shopInfo.getId(), distance);
            }

            HashMap<String, Integer> hashMap1 = MapUtil.sortHashMap(hashMap);
            List<ShopInfo> shopInfos1 = new ArrayList<>();
            for (String key : hashMap1.keySet()) {
                ShopInfo shopInfo = shopInfoRepository.findOne(key);
                Salesman salesman = salesmanRepository.findOne(shopInfo.getSalesmanId());
                shopInfo.setSalesmanPhone(salesman.getPhone());
                shopInfo.setSalesmanName(salesman.getName());
                List<ShoppingApply> shoppingApplies = shoppingApplyRepository.findAllByMiniUserIdAndShopIdAndIsApplyAndDelFlag(miniUserId, key, "1", "0");
                if (shoppingApplies.size() > 0) {
                    shopInfo.setState("1");
                } else {
                    shopInfo.setState("0");
                }
                shopInfos1.add(shopInfo);
            }
            apiResultBean.setData(shopInfos1, antPage, shopInfos.getTotalElements());
            apiResultBean.setCode(ApiResultBean.SUCCESS);
            apiResultBean.setMsg("查询成功");
            return apiResultBean;
        } else {
            return apiResultBean;
        }

    }


    public ApiResultBean queryAllGoods(String shoppingId, AntPage antPage) {
        ApiResultBean apiResultBean = new ApiResultBean();
        Shopping shopping = shoppingRepository.findOne(shoppingId);
        Page<ShopLibory> shoppingLibories = shoppingLiboryRepository.findAllByShopIdAndDelFlag(shopping.getShopId(), "0", antPage.getPageRequest());

        List<MiniShoppingGoodsVo> miniShoppingGoodsVos = new ArrayList<>();
        for (ShopLibory shoppingLibory : shoppingLibories) {
            MiniShoppingGoodsVo miniShoppingGoodsVo = new MiniShoppingGoodsVo();
            Goods goods = goodsRepository.findOne(shoppingLibory.getGoodsId());
            miniShoppingGoodsVo.setGoodsId(goods.getId());
            miniShoppingGoodsVo.setGoodsImage(goods.getImages());
            miniShoppingGoodsVo.setGoodsName(goods.getName());
            miniShoppingGoodsVo.setRemark(goods.getRemark());
            miniShoppingGoodsVo.setResidueNum(shoppingLibory.getGoodsNum());
            miniShoppingGoodsVo.setThreshold(goods.getThreshold());
            miniShoppingGoodsVo.setSpecification(goods.getSpecification());
            miniShoppingGoodsVos.add(miniShoppingGoodsVo);
        }
        HashMap<String, String> hashMap = new HashMap<>();
        ShopInfo shopInfo = shopInfoRepository.findOne(shopping.getShopId());
        hashMap.put("isPerpetual", shopping.getIsPerpetual());
        hashMap.put("subjection", shopInfo.getName() + shopping.getName());
        if (shopping.getIsPerpetual().equals("1")) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            hashMap.put("startTime", df.format(shopping.getStartTime()));
            hashMap.put("endTime", df.format(shopping.getEndTime()));
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        hashMap.put("createTime", df.format(shopping.getCreateTime()));
        apiResultBean.setData(hashMap);
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setData(miniShoppingGoodsVos, antPage, shoppingLibories.getTotalElements());
        return apiResultBean;
    }

    public ApiResultBean getGoodGift(String goodGiftId, String longitude, String latitude) {
        ApiResultBean apiResultBean = new ApiResultBean();
        GoodsGift goodsGift = goodsGiftRepository.findAllByIdAndDelFlag(goodGiftId, "0");
        if (goodsGift != null) {
            //判断用户经纬度和店铺经纬度的距离


            if (goodsGift.getState().equals("1")) {
                apiResultBean.setCode(ApiResultBean.FAIL);
                apiResultBean.setMsg("二维码已失效");
                return apiResultBean;
            } else {
                //保存赠品记录
                goodsGift.setUserOpenId(goodsGift.getUserOpenId());
                goodsGift.setState("1");
                goodsGift.setGetTime(new Date());
                goodsGiftRepository.saveAndFlush(goodsGift);
                Goods goods = goodsRepository.findAllByIdAndDelFlag(goodsGift.getGoodsId(), "0");
                Shopping shopping = shoppingRepository.findOne(goodsGift.getShoppingId());
                List<ShopLibory> shoppingLibory = shoppingLiboryRepository.findAllByShopIdAndDelFlag(shopping.getShopId(), "0");
                if (shoppingLibory.size() > 0) {
                    if (shoppingLibory.get(0).getGoodsNum() > 0) {
                        //更新导购赠品库数量
                        shoppingLibory.get(0).setGoodsNum(shoppingLibory.get(0).getGoodsNum() - 1);
                        //添加导购赠品更换记录
                        ShoppingGiftChangeLog shoppingGiftChangeLog = new ShoppingGiftChangeLog();
                        shoppingGiftChangeLog.setGiftChange(GiftChange.GRANT);

                        shoppingGiftChangeLog.setChangeNum(1);
                        shoppingGiftChangeLogRepository.save(shoppingGiftChangeLog);
                    } else {
                        apiResultBean.setCode(ApiResultBean.FAIL);
                        apiResultBean.setMsg("二维码已失效");
                        return apiResultBean;
                    }

                }
            }

        }
        return apiResultBean;
    }

    public ApiResultBean getCode(String shoppingId, String goodsId) {
        ApiResultBean apiResultBean = new ApiResultBean();

        Shopping shopping = shoppingRepository.findOne(shoppingId);
        String shopId = shopping.getShopId();


        if (StringUtil.isEmpty(shoppingId) && StringUtil.isEmpty(goodsId)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("导购id和赠品id不能为空");
            return apiResultBean;
        }

        ShopInfo shopInfo = shopInfoRepository.findOne(shopId);
        GoodsGift goodsGift = new GoodsGift();
        goodsGift.setGoodsId(goodsId);
        goodsGift.setShoppingId(shoppingId);
        goodsGift.setShopId(shopId);
        goodsGift.setSalesmanId(shopInfo.getSalesmanId());
        goodsGift.setState("0");
        goodsGiftRepository.saveAndFlush(goodsGift);
        String aa = "";
        String ticket = "";
        try {
            String accessToken = WechatMiniConfig.getAccessToken1();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("expire_seconds", 120);
            jsonObject.put("action_name", "QR_STR_SCENE");
            JSONObject actionInfo = new JSONObject();
            JSONObject scene = new JSONObject();
            scene.put("scene_str", goodsGift.getId());
            //  scene.put("scene_id", "1131361614654655");
            actionInfo.put("scene", scene);
            jsonObject.put("action_info", actionInfo);
            String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
            String result = HttpClientUtil.doPostJson(url, jsonObject.toJSONString());
            JSONObject resultJson = JSONObject.parseObject(result);
            ticket = resultJson.getString("ticket");
            aa = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + URLEncoder.encode(ticket, "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        goodsGift.setCode(aa);
        goodsGiftRepository.save(goodsGift);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("code", aa);
        apiResultBean.setData(hashMap);
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;

    }

    public ApiResultBean shoppingApply(String minUserId, String shopId, String isPerpetual, Date start, Date end) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(minUserId) || StringUtil.isEmpty(shopId)) {
            apiResultBean.setMsg("minUserId或者shopId为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return apiResultBean;
        }
        List<ShoppingApply> shoppingApplies = shoppingApplyRepository.findAllByMiniUserIdAndIsApplyAndDelFlag(minUserId, "1", "0");
        if (shoppingApplies.size() > 0) {
            apiResultBean.setMsg("你已经申请过了");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return apiResultBean;
        }
        ShopInfo shopInfo = shopInfoRepository.findOne(shopId);
        ShoppingApply shoppingApply = new ShoppingApply();
        shoppingApply.setMiniUserId(minUserId);
        shoppingApply.setSalesmanId(shopInfo.getSalesmanId());
        shoppingApply.setIsApply("1");
        shoppingApply.setShopId(shopId);
        shoppingApply.setIsPerpetual(isPerpetual);
        if (isPerpetual.equals("1")) {
            shoppingApply.setStartTime(start);
            shoppingApply.setEndTime(end);
        }
        shoppingApplyRepository.saveAndFlush(shoppingApply);
        apiResultBean.setMsg("申请成功，请静候业务员同意");
        apiResultBean.setCode(ApiResultBean.SUCCESS);

        return apiResultBean;
    }


    public ApiResultBean queryUserLog(String shoppingId, AntPage antPage) {
        ApiResultBean apiResultBean = new ApiResultBean();
        Shopping shopping = shoppingRepository.findOne(shoppingId);
        //去重得到用户openid
        List<String> strings = goodsGiftRepository.findDistinctByUserOpenIdAndDelFlagAndState("1", "0", shopping.getShopId(), (antPage.getPage() - 1) * antPage.getPageSize(), antPage.getPageSize());
        List<String> strings1 = goodsGiftRepository.findDistinctByUserOpenId("1", "0", shopping.getShopId());
        List<HistoryUserLogVo> historyUserLogs = new ArrayList<>();
        for (String str : strings) {
            HistoryUserLogVo historyUserLog = new HistoryUserLogVo();
            List<UserInfo> userInfos = userInfoRepository.findAllByOppenIdAndDelFlag(str, "0");
            if (userInfos.size() > 0) {
                historyUserLog.setImages(userInfos.get(0).getHeadimgurl());
                historyUserLog.setNikName(userInfos.get(0).getNickname());
                historyUserLog.setUserOpenId(userInfos.get(0).getOppenId());
            }
            int getNum = goodsGiftRepository.countAllByUserOpenIdAndDelFlagAndState(str, "0", "1");
            historyUserLog.setGetNum(getNum);

            historyUserLogs.add(historyUserLog);
        }

        apiResultBean.setMsg("查看成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setData(historyUserLogs, antPage, Long.valueOf(strings1.size()));
        return apiResultBean;
    }

    public ApiResultBean userHistoryLog(String userOpenid, AntPage antPage) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(userOpenid)) {
            apiResultBean.setMsg("用户openid不能为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return apiResultBean;
        }
        Page<GoodsGift> goodsGifts = goodsGiftRepository.findAllByUserOpenIdAndDelFlagAndState(userOpenid, "0", "1", antPage.getPageRequest());
        List<HistoryUserLogVo> historyUserLogs = new ArrayList<>();
        if (goodsGifts.getSize() > 0) {
            for (GoodsGift goodsGift : goodsGifts) {
                HistoryUserLogVo historyUserLog = new HistoryUserLogVo();
                String goodsId = goodsGift.getGoodsId();
                String shopId = goodsGift.getShopId();
                String userOpenId = goodsGift.getUserOpenId();
                List<UserInfo> userInfos = userInfoRepository.findAllByOppenIdAndDelFlag(userOpenId, "0");
                Goods goods = goodsRepository.findOne(goodsId);
                ShopInfo shopInfo = shopInfoRepository.findOne(shopId);
                Shopping shopping = shoppingRepository.findOne(goodsGift.getShoppingId());
                if (userInfos.size() > 0) {
                    historyUserLog.setNikName(userInfos.get(0).getNickname());
                }
                historyUserLog.setGetTime(goodsGift.getModifyTime());
                historyUserLog.setGoodsName(goods.getName());
                //   historyUserLog.setGoodsSpecification(giftGoods.getSpecification());
                historyUserLog.setShopName(shopInfo.getName());
                //   historyUserLog.setThreshold(giftGoods.getThreshold());
                historyUserLog.setImages(userInfos.get(0).getHeadimgurl());
                //    historyUserLog.setShopImages(shopInfo.getImagePath());
                historyUserLog.setShoppingName(shopping.getName());
                historyUserLogs.add(historyUserLog);


            }
        }
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setMsg("查看成功");
        apiResultBean.setData(historyUserLogs, antPage, goodsGifts.getTotalElements());
        return apiResultBean;
    }

    public ApiResultBean queryApply(String minUserId) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(minUserId)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("minUserId不能为空");
            return apiResultBean;

        }
        List<ShoppingApply> shoppingApplies = shoppingApplyRepository.findAllByMiniUserIdAndIsApplyAndDelFlag(minUserId, "1", "0");
        if (shoppingApplies.size() > 0) {
            ShopInfo shopInfo = shopInfoRepository.findOne(shoppingApplies.get(0).getShopId());
            Salesman salesman = salesmanRepository.findOne(shopInfo.getSalesmanId());
            shopInfo.setSalesmanName(salesman.getName());
            shopInfo.setSalesmanPhone(salesman.getPhone());
            apiResultBean.setCode(ApiResultBean.SUCCESS);
            apiResultBean.setData(shopInfo);
        } else {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("错误");
            return apiResultBean;
        }
        return apiResultBean;
    }

    public ApiResultBean queryGoodsGetLog(String goodsId, String shoppingId, String shopId, AntPage antPage, String startTime, String endTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startTime);
            end = sdf.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(goodsId)) {
            apiResultBean.setMsg("goodsId不能为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return apiResultBean;
        }
        Shopping shopping = shoppingRepository.findOne(shoppingId);
        if(StringUtil.isEmpty(shopId)){
            shopId=shopping.getShopId();
        }
        Page<GoodsGift> goodsGifts = null;
        goodsGifts = goodsGiftRepository.findAllByGoodsIdAndShoppingIdAndShopIdContainsAndDelFlagAndStateAndCreateTimeBetweenOrderByCreateTimeDesc(goodsId, shoppingId, shopId, "0", "1", start, end, antPage.getPageRequest());



        ShopInfo shopInfo = shopInfoRepository.findOne(shopping.getShopId());
        Goods goods = goodsRepository.findOne(goodsId);
        HashMap<String, String> hashMap = new HashMap<>();
        List<ShopLibory> shopLibories = shoppingLiboryRepository.findAllByShopIdAndGoodsIdAndDelFlag(shopInfo.getId(), goodsId, "0");
        if (shopLibories.size() > 0) {
            hashMap.put("goodsNum", String.valueOf(shopLibories.get(0).getGoodsNum()));
        }
        int totalNums = goodsGiftRepository.countshopandgoodNum(shopInfo.getId(), goodsId, "1", "0");
        hashMap.put("totalNums", String.valueOf(goodsGifts.getTotalElements()));
        //  hashMap.put("name", giftGoods.getName());
        hashMap.put("imagePath", goods.getImages());
        hashMap.put("shoppingNums", String.valueOf(goodsGifts.getTotalElements()));
        hashMap.put("remark", goods.getRemark());
        hashMap.put("goodsName", goods.getName());

        List<HistoryUserLogVo> historyUserLogVos = new ArrayList<>();
        if (goodsGifts.getSize() > 0) {

            for (GoodsGift goodsGift : goodsGifts) {
                HistoryUserLogVo historyUserLogVo = new HistoryUserLogVo();
                List<UserInfo> userInfos = userInfoRepository.findAllByOppenIdAndDelFlag(goodsGift.getUserOpenId(), "0");
                historyUserLogVo.setImages(userInfos.get(0).getHeadimgurl());
                historyUserLogVo.setNikName(userInfos.get(0).getNickname());
                historyUserLogVo.setGetTime(goodsGift.getModifyTime());
                historyUserLogVo.setTime(shopping.getCreateTime());
                historyUserLogVos.add(historyUserLogVo);

            }
        }


        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setData(hashMap);
        apiResultBean.setData(historyUserLogVos, antPage, goodsGifts.getTotalElements());
        return apiResultBean;
    }

    public ApiResultBean cancelApply(String miniUserId) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(miniUserId)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("参数为空");
            return apiResultBean;
        }
        List<ShoppingApply> shoppingApplies = shoppingApplyRepository.findAllByMiniUserIdAndIsApplyAndDelFlag(miniUserId, "1", "0");
        if (shoppingApplies.size() > 0) {
            shoppingApplies.get(0).setDelFlag("1");
            shoppingApplyRepository.saveAndFlush(shoppingApplies.get(0));
        }
        return apiResultBean;
    }

    public ApiResultBean goodsDetails(String shoppingId, String goodsId) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(shoppingId) || StringUtil.isEmpty(goodsId)) {
            apiResultBean.setMsg("参数为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return apiResultBean;
        }
        Shopping shopping = shoppingRepository.findOne(shoppingId);
        Goods goods = goodsRepository.findOne(goodsId);
        ApiResultBean code = getCode(shoppingId, goodsId);
        Object object = code.getData().getObject();
        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(object);
        String path = jsonObject.getString("code");
        GoodsDetailsVo goodsDetailsVo = new GoodsDetailsVo();
        goodsDetailsVo.setCode(path);
        goodsDetailsVo.setGoodsImage(goods.getImages());
        goodsDetailsVo.setGoodsName(goods.getName());
        goodsDetailsVo.setRemark(goods.getRemark());

        List<ShopLibory> shopLibories = shoppingLiboryRepository.findAllByShopIdAndGoodsIdAndDelFlag(shopping.getShopId(), goodsId, "0");
        if (shopLibories.size() > 0) {
            goodsDetailsVo.setGoodsNum(shopLibories.get(0).getGoodsNum());
        }
        apiResultBean.setData(goodsDetailsVo);
        return apiResultBean;
    }

    public ApiResultBean miniQueryHistoryShop(String shoppingId) {

        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(shoppingId)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("id不能为空");
            return apiResultBean;
        }
        Shopping shopping = shoppingRepository.findOne(shoppingId);
        List<ShoppingChangeLog> shoppingChangeLogs = shoppingChangeLogRepository.findAllByShoppingIdAndDelFlagOrderByCreateTimeDesc(shoppingId, "0");
        int a = shoppingChangeLogRepository.countAllByShoppingIdAndDelFlag(shoppingId, "0");
        List<HistoryShopVo> historyShopVos = new ArrayList<>();
        if (shoppingChangeLogs.size() > 0) {
            for (ShoppingChangeLog shoppingChangeLog : shoppingChangeLogs) {
                HistoryShopVo historyShopVo = new HistoryShopVo();
                historyShopVo.setJoinTime(shoppingChangeLog.getCreateTime());
                ShopInfo shopInfo = shopInfoRepository.findOne(shoppingChangeLog.getShopId());
                historyShopVo.setShopName(shopInfo.getName());
                historyShopVo.setAddress(shopInfo.getAddress());
                historyShopVo.setShopId(shopInfo.getId());
                if (shoppingChangeLog.getShopId().equals(shopping.getShopId())) {
                    historyShopVo.setIsCurrent("1");
                }else {
                    historyShopVo.setIsCurrent("0");
                }

                historyShopVos.add(historyShopVo);
            }
        }
        apiResultBean.setMsg("查询成功");
        apiResultBean.setData(historyShopVos);
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }

    public ApiResultBean shoppingStatistics(String shoppingId, AntPage antPage, String shopId, String startTime, String endTime) {
        ApiResultBean apiResultBean = new ApiResultBean();

        if (StringUtil.isEmpty(shoppingId)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("参数为空");
            return apiResultBean;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startTime);
            end = sdf.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Shopping shopping = shoppingRepository.findOne(shoppingId);
        if(StringUtil.isEmpty(shopId)){
            shopId=shopping.getShopId();
        }

        //店铺下的赠品
        Page<ShopLibory> strings = shoppingLiboryRepository.findAllByShopIdAndDelFlag(shopId, "0", antPage.getPageRequest());

        Page<GoodsGift> goodsGifts = goodsGiftRepository.findAllByShoppingIdAndDelFlagAndStateAndShopIdContainsAndCreateTimeBetweenOrderByModifyName(shoppingId, "0", "1", shopId, start, end, antPage.getPageRequest());
        List<StatisticsVo> statisticsVos = new ArrayList<>();

        if (strings.getSize() > 0) {
            //根据每个赠品查值
            for (ShopLibory shopLibory : strings) {
                StatisticsVo statisticsVo = new StatisticsVo();
                //每个赠品的在店铺的导购的赠品信息s
                Goods goods = goodsRepository.findOne(shopLibory.getGoodsId());

                statisticsVo.setGoodsname(goods.getName());
                statisticsVo.setGoodsImage(goods.getImages());
                statisticsVo.setGoodsId(goods.getId());
                statisticsVo.setShopGoodsNum(shopLibory.getGoodsNum());

                List<String> strings1 = goodsGiftRepository.countshopandgood(shopId, shopLibory.getGoodsId(), "1", "0", shoppingId, start, end);
                statisticsVo.setUserGetNum(strings1.size());
                List<GoodsGift> goodsGifts1 = goodsGiftRepository.findAllByShopIdAndShoppingIdAndDelFlagAndStateAndGoodsIdAndCreateTimeBetween(shopping.getShopId(), shoppingId, "0", "1",goods.getId(), start, end);
                statisticsVo.setGiftSendNum(goodsGifts1.size());
                statisticsVos.add(statisticsVo);
            }
        }

        HashMap<String, Integer> hashMap = new HashMap<>();
       int sumSend = goodsGiftRepository.countDistinctByGoodsId(shopId, "1", "0", shoppingId);
        hashMap.put("sumSend",sumSend);

        apiResultBean.setData(hashMap);
        apiResultBean.setData(statisticsVos, antPage, strings.getTotalElements());
        return apiResultBean;
    }

    public ApiResultBean shoppingAdmin(String salesmanId,AntPage antPage,String field){
        ApiResultBean apiResultBean=new ApiResultBean();
        if(StringUtil.isEmpty(salesmanId)){
            apiResultBean.setMsg("参数不能为空");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return  apiResultBean;
        }

       Page<Shopping> shoppings=shoppingRepository.findAllBySalesmanIdAndDelFlagAndNameContainsOrderByCreateTime(salesmanId,"0",field,antPage.getPageRequest());
        Page<Shopping> shoppings1=shoppingRepository.findAllBySalesmanIdAndDelFlagAndPhoneContainsOrderByCreateTime(salesmanId,"0",field,antPage.getPageRequest());
        List<Shopping> shoppings2=new ArrayList<>();


        if(shoppings.getSize()>0){
            for (Shopping shopping: shoppings ) {
                shoppings2.add(shopping);
            }
        }

        if(shoppings1.getSize()>0){
            for (Shopping shopping: shoppings1 ) {
                shoppings2.add(shopping);
            }
        }

        Set<Shopping> set=new HashSet<>();
        set.addAll(shoppings2);


        if(set.size()>0){
            for (Shopping shopping:shoppings ) {
                int a=goodsGiftRepository.countShoppingNum(shopping.getId(),"1","0");
                shopping.setGetNum(a);
                ShopInfo shopInfo=shopInfoRepository.findAllByDelFlagAndId("0",shopping.getShopId());
                shopping.setShopName(shopInfo.getName());
                shopping.setShopId(shopInfo.getId());
            }
        }
        List<Shopping> shoppings3=new ArrayList<>();
        shoppings3.addAll(set);

        apiResultBean.setMsg("成功");
        apiResultBean.setData(shoppings3,antPage,shoppings.getTotalElements()+shoppings.getTotalElements());
        return  apiResultBean;
    }

    public ApiResultBean salesamanAddShopping(Shopping shopping){
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(shopping.getName())) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("姓名不能为空");
            return apiResultBean;
        }
        if (StringUtil.isEmpty(shopping.getPhone())) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("手机号不能为空");
            return apiResultBean;
        }
        if (StringUtil.isEmpty(shopping.getIsPerpetual())) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("临时导购字段不能为空不能为空");
            return apiResultBean;
        }
        if (StringUtil.isEmpty(shopping.getShopId())) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("店铺id不能为空");
            return apiResultBean;
        }

        Shopping shopping1 = new Shopping();
        shopping1.setName(shopping.getName());
        shopping1.setPhone(shopping.getPhone());
        shopping1.setIsPerpetual(shopping.getIsPerpetual());
        if (shopping.getIsPerpetual().equals("1")) {
            shopping1.setEndTime(shopping.getEndTime());
            shopping1.setStartTime(shopping.getStartTime());
        }
        shopping1.setShopId(shopping.getShopId());
        ShopInfo shopInfo = shopInfoRepository.findOne(shopping.getShopId());
        shopping1.setSalesmanId(shopInfo.getSalesmanId());
        shoppingRepository.save(shopping1);

        ShoppingChangeLog shoppingChangeLog = new ShoppingChangeLog();
        shoppingChangeLog.setShoppingId(shopping1.getId());
        shoppingChangeLog.setShopId(shopping.getShopId());
        shoppingChangeLogRepository.saveAndFlush(shoppingChangeLog);


        apiResultBean.setMsg("添加成功");
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        return apiResultBean;
    }


}